package com.lagou.handler;

import com.alibaba.fastjson.JSON;
import com.lagou.annotation.Component;
import com.lagou.ioc.ApplicationContext;
import com.lagou.ioc.ApplicationContextAware;
import com.lagou.server.ZkProxy;
import com.lagou.service.NodeContentInfo;
import com.lagou.service.RpcRequest;
import com.lagou.service.UserService;
import com.lagou.service.UserServiceImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.curator.framework.CuratorFramework;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Random;

@Component
public class UserServerHandler extends ChannelInboundHandlerAdapter implements ApplicationContextAware {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        // 判断是否符合约定，符合则调用本地方法，返回数据
        // msg:  UserService#sayHello#are you ok?
        long start = System.nanoTime();
        try {
            RpcRequest rpcRequest = (RpcRequest) msg;
            UserService userService = (UserService) ac.getBean(rpcRequest.getClassName());
            Method[] methods = userService.getClass().getMethods();
            a:for (Method method : methods) {
                if (method.getName().equals(rpcRequest.getMethodName())) {
                    Class<?>[] parameterTypes = method.getParameterTypes();
                    for (int i = 0; i < parameterTypes.length; i++) {
                        if (parameterTypes[i] != rpcRequest.getParameterTypes()[i]) {
                            break a;
                        }
                    }
                    //通过反射执行任务
                    Object invoke = method.invoke(userService, rpcRequest.getParameters());
                    System.out.println("执行完成:" + invoke);
                    ctx.writeAndFlush(invoke);
                    System.out.println("服务端返回执行结果");
                    return;
                }
            }
            Random random = new Random();
            Thread.sleep(random.nextInt(100));
        }finally {
            //更新节点信息
            CuratorFramework client = ZkProxy.getClient();
            NodeContentInfo nodeInfo = new NodeContentInfo(ZkProxy.IP, ZkProxy.PORT,System.nanoTime()-start, System.nanoTime());
            client.setData().forPath(ZkProxy.ZK_NODE_PATH, JSON.toJSONString(nodeInfo).getBytes());
        }
    }

    private static ApplicationContext ac = null;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        ac = applicationContext;
    }
}
